package com.gange.mybatis.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtils {
    private static SqlSessionFactory ssf = null;
    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();
    static{
        //1.读取mybatis-config.xml
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //2.获取SqlSessionFactory对象,工厂模式，帮助我们创建数据库连接
        ssf = new SqlSessionFactoryBuilder().build( is );
    }
    public static SqlSession getSession(){
        SqlSession sqlSession = tl.get();
        if(sqlSession!=null) return sqlSession;
        sqlSession = ssf.openSession();
        tl.set(sqlSession);
        return sqlSession;
    }

    public static void closeSession(){
        SqlSession session = getSession();
        if(session!=null) {
            tl.remove();
            session.close();
        }
    }
}
